<template>
  <div class="transition-editor-container">
    <n-card class="transition-card">
      <template #header>
        <div class="card-header">
          <h1>过渡效果编辑器</h1>
          <div class="header-actions">
            <n-button @click="saveTransition" type="primary">
              <template #icon><n-icon><SaveOutline /></n-icon></template>
              保存过渡效果
            </n-button>
            <n-button @click="goBack">
              <template #icon><n-icon><ArrowBackOutline /></n-icon></template>
              返回
            </n-button>
          </div>
        </div>
      </template>
      
      <div class="content-layout">
        <div class="preview-section">
          <div class="preview-header">
            <h3>过渡预览</h3>
            <n-space>
              <n-button size="small" @click="playPreview">
                <template #icon><n-icon><PlayOutline /></n-icon></template>
                播放
              </n-button>
              <n-button size="small" @click="resetPreview">
                <template #icon><n-icon><RefreshOutline /></n-icon></template>
                重置
              </n-button>
            </n-space>
          </div>
          
          <div class="preview-container">
            <div class="scene-preview">
              <div class="scene-from" :style="{ opacity: previewProgress > 0.5 ? 1 - previewProgress * 2 + 1 : 1 }">
                <img :src="fromSceneThumbnail" alt="起始场景" />
              </div>
              <div class="scene-to" :style="{ opacity: previewProgress }">
                <img :src="toSceneThumbnail" alt="目标场景" />
              </div>
              <div class="transition-overlay" v-if="isPlaying">
                <div class="transition-effect" :class="[`effect-${currentTransition.type}`]"></div>
              </div>
            </div>
            
            <div class="preview-controls">
              <n-slider
                v-model:value="previewProgress"
                :min="0"
                :max="1"
                :step="0.01"
              />
              <div class="progress-labels">
                <span>起始场景</span>
                <span>目标场景</span>
              </div>
            </div>
          </div>
        </div>
        
        <div class="settings-section">
          <n-tabs type="line" animated>
            <n-tab-pane name="basic" tab="基本设置">
              <div class="tab-content">
                <n-form
                  :model="transitionForm"
                  label-placement="left"
                  label-width="100"
                  require-mark-placement="right-hanging"
                >
                  <n-form-item label="过渡名称" path="name">
                    <n-input v-model:value="transitionForm.name" placeholder="输入过渡效果名称" />
                  </n-form-item>
                  
                  <n-form-item label="过渡类型" path="type">
                    <n-select
                      v-model:value="transitionForm.type"
                      :options="transitionTypeOptions"
                      @update:value="handleTransitionTypeChange"
                    />
                  </n-form-item>
                  
                  <n-form-item label="持续时间" path="duration">
                    <n-input-number
                      v-model:value="transitionForm.duration"
                      :min="100"
                      :max="5000"
                      :step="100"
                    >
                      <template #suffix>毫秒</template>
                    </n-input-number>
                  </n-form-item>
                  
                  <n-form-item label="缓动函数" path="easing">
                    <n-select
                      v-model:value="transitionForm.easing"
                      :options="easingOptions"
                    />
                  </n-form-item>
                </n-form>
              </div>
            </n-tab-pane>
            
            <n-tab-pane name="advanced" tab="高级设置">
              <div class="tab-content">
                <template v-if="transitionForm.type === 'fade'">
                  <h3>淡入淡出设置</h3>
                  <n-form-item label="透明度曲线">
                    <n-select
                      v-model:value="transitionForm.options.fadeType"
                      :options="fadeTypeOptions"
                    />
                  </n-form-item>
                </template>
                
                <template v-if="transitionForm.type === 'slide'">
                  <h3>滑动设置</h3>
                  <n-form-item label="滑动方向">
                    <n-select
                      v-model:value="transitionForm.options.direction"
                      :options="slideDirectionOptions"
                    />
                  </n-form-item>
                </template>
                
                <template v-if="transitionForm.type === 'zoom'">
                  <h3>缩放设置</h3>
                  <n-form-item label="缩放类型">
                    <n-select
                      v-model:value="transitionForm.options.zoomType"
                      :options="zoomTypeOptions"
                    />
                  </n-form-item>
                  <n-form-item label="缩放倍率">
                    <n-slider
                      v-model:value="transitionForm.options.scale"
                      :min="0.5"
                      :max="2"
                      :step="0.1"
                    />
                  </n-form-item>
                </template>
                
                <template v-if="transitionForm.type === 'wipe'">
                  <h3>擦除设置</h3>
                  <n-form-item label="擦除方向">
                    <n-select
                      v-model:value="transitionForm.options.direction"
                      :options="wipeDirectionOptions"
                    />
                  </n-form-item>
                  <n-form-item label="边缘模糊">
                    <n-slider
                      v-model:value="transitionForm.options.feather"
                      :min="0"
                      :max="50"
                      :step="1"
                    />
                  </n-form-item>
                </template>
                
                <template v-if="transitionForm.type === 'custom'">
                  <h3>自定义设置</h3>
                  <n-alert title="高级功能" type="info">
                    自定义过渡效果需要使用 CSS 或 WebGL 着色器。请在下方编辑代码。
                  </n-alert>
                  <n-form-item label="CSS 代码" style="margin-top: 16px;">
                    <n-input
                      v-model:value="transitionForm.options.customCss"
                      type="textarea"
                      :autosize="{ minRows: 5, maxRows: 10 }"
                      placeholder="输入自定义 CSS 代码..."
                    />
                  </n-form-item>
                </template>
              </div>
            </n-tab-pane>
          </n-tabs>
        </div>
      </div>
      
      <n-divider />
      
      <div class="scene-selection">
        <h3>场景选择</h3>
        <div class="scene-selector-container">
          <div class="scene-selector">
            <h4>起始场景</h4>
            <div class="scene-thumbnail">
              <img :src="fromSceneThumbnail" alt="起始场景" />
            </div>
            <n-button size="small" @click="selectFromScene">
              选择场景
            </n-button>
          </div>
          
          <div class="transition-arrow">
            <n-icon size="32"><ArrowForwardOutline /></n-icon>
          </div>
          
          <div class="scene-selector">
            <h4>目标场景</h4>
            <div class="scene-thumbnail">
              <img :src="toSceneThumbnail" alt="目标场景" />
            </div>
            <n-button size="small" @click="selectToScene">
              选择场景
            </n-button>
          </div>
        </div>
      </div>
      
      <!-- 场景选择对话框 -->
      <n-modal
        v-model:show="showSceneSelector"
        preset="dialog"
        title="选择场景"
        style="width: 600px"
      >
        <n-grid :cols="3" :x-gap="12" :y-gap="12">
          <n-grid-item v-for="scene in availableScenes" :key="scene.id">
            <div
              class="scene-select-item"
              :class="{ 'selected': selectedSceneId === scene.id }"
              @click="handleSceneSelect(scene)"
            >
              <img :src="scene.thumbnail" :alt="scene.name" />
              <span>{{ scene.name }}</span>
            </div>
          </n-grid-item>
        </n-grid>
        
        <template #action>
          <n-button @click="cancelSceneSelection">
            取消
          </n-button>
          <n-button type="primary" @click="confirmSceneSelection">
            确认
          </n-button>
        </template>
      </n-modal>
    </n-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useMessage } from 'naive-ui'
import {
  NCard,
  NButton,
  NIcon,
  NSpace,
  NTabs,
  NTabPane,
  NForm,
  NFormItem,
  NInput,
  NInputNumber,
  NSelect,
  NSlider,
  NDivider,
  NGrid,
  NGridItem,
  NModal,
  NAlert
} from 'naive-ui'
import {
  SaveOutline,
  ArrowBackOutline,
  PlayOutline,
  RefreshOutline,
  ArrowForwardOutline
} from '@vicons/ionicons5'

const router = useRouter()
const message = useMessage()

// 预览状态
const isPlaying = ref(false)
const previewProgress = ref(0)
const previewTimer = ref<number | null>(null)

// 场景缩略图
const fromSceneThumbnail = ref('https://picsum.photos/id/1015/400/225')
const toSceneThumbnail = ref('https://picsum.photos/id/1018/400/225')

// 场景选择
const showSceneSelector = ref(false)
const selectedSceneId = ref('')
const isSelectingFromScene = ref(true)

// 过渡表单
const transitionForm = reactive({
  name: '新建过渡效果',
  type: 'fade',
  duration: 1000,
  easing: 'ease',
  options: {
    fadeType: 'crossfade',
    direction: 'left',
    zoomType: 'in',
    scale: 1.5,
    feather: 10,
    customCss: ''
  }
})

// 当前过渡效果
const currentTransition = computed(() => ({
  ...transitionForm,
  fromScene: fromSceneThumbnail.value,
  toScene: toSceneThumbnail.value
}))

// 过渡类型选项
const transitionTypeOptions = [
  { label: '淡入淡出', value: 'fade' },
  { label: '滑动', value: 'slide' },
  { label: '缩放', value: 'zoom' },
  { label: '擦除', value: 'wipe' },
  { label: '自定义', value: 'custom' }
]

// 缓动函数选项
const easingOptions = [
  { label: '线性', value: 'linear' },
  { label: '缓入', value: 'ease-in' },
  { label: '缓出', value: 'ease-out' },
  { label: '缓入缓出', value: 'ease-in-out' },
  { label: '弹性', value: 'cubic-bezier(0.68, -0.55, 0.27, 1.55)' }
]

// 淡入淡出选项
const fadeTypeOptions = [
  { label: '交叉淡入淡出', value: 'crossfade' },
  { label: '淡入', value: 'fade-in' },
  { label: '淡出', value: 'fade-out' },
  { label: '溶解', value: 'dissolve' }
]

// 滑动方向选项
const slideDirectionOptions = [
  { label: '从左向右', value: 'left' },
  { label: '从右向左', value: 'right' },
  { label: '从上向下', value: 'top' },
  { label: '从下向上', value: 'bottom' }
]

// 缩放类型选项
const zoomTypeOptions = [
  { label: '放大', value: 'in' },
  { label: '缩小', value: 'out' },
  { label: '放大并淡入', value: 'in-fade' },
  { label: '缩小并淡出', value: 'out-fade' }
]

// 擦除方向选项
const wipeDirectionOptions = [
  { label: '从左向右', value: 'left-to-right' },
  { label: '从右向左', value: 'right-to-left' },
  { label: '从上向下', value: 'top-to-bottom' },
  { label: '从下向上', value: 'bottom-to-top' },
  { label: '中心扩展', value: 'center-out' },
  { label: '边缘收缩', value: 'edge-in' }
]

// 模拟场景数据
const availableScenes = [
  { id: 'scene1', name: '场景 1', thumbnail: 'https://picsum.photos/id/1015/200/120' },
  { id: 'scene2', name: '场景 2', thumbnail: 'https://picsum.photos/id/1018/200/120' },
  { id: 'scene3', name: '场景 3', thumbnail: 'https://picsum.photos/id/1019/200/120' },
  { id: 'scene4', name: '场景 4', thumbnail: 'https://picsum.photos/id/1021/200/120' },
  { id: 'scene5', name: '场景 5', thumbnail: 'https://picsum.photos/id/1022/200/120' }
]

// 处理过渡类型变更
const handleTransitionTypeChange = (value: string) => {
  // 根据类型重置相关选项
  if (value === 'fade') {
    transitionForm.options.fadeType = 'crossfade'
  } else if (value === 'slide') {
    transitionForm.options.direction = 'left'
  } else if (value === 'zoom') {
    transitionForm.options.zoomType = 'in'
    transitionForm.options.scale = 1.5
  } else if (value === 'wipe') {
    transitionForm.options.direction = 'left-to-right'
    transitionForm.options.feather = 10
  } else if (value === 'custom') {
    transitionForm.options.customCss = `/* 自定义过渡效果 CSS */
.custom-transition {
  transition: all ${transitionForm.duration}ms ${transitionForm.easing};
}`
  }
}

// 播放预览
const playPreview = () => {
  resetPreview()
  isPlaying.value = true
  
  // 清除之前的计时器
  if (previewTimer.value !== null) {
    clearInterval(previewTimer.value)
  }
  
  // 设置新的计时器
  const startTime = Date.now()
  previewTimer.value = window.setInterval(() => {
    const elapsed = Date.now() - startTime
    const progress = elapsed / transitionForm.duration
    
    if (progress >= 1) {
      previewProgress.value = 1
      clearInterval(previewTimer.value as number)
      previewTimer.value = null
      
      // 延迟一段时间后重置预览
      setTimeout(() => {
        isPlaying.value = false
      }, 500)
    } else {
      previewProgress.value = progress
    }
  }, 16) // 约60fps
}

// 重置预览
const resetPreview = () => {
  if (previewTimer.value !== null) {
    clearInterval(previewTimer.value)
    previewTimer.value = null
  }
  
  previewProgress.value = 0
  isPlaying.value = false
}

// 场景选择
const selectFromScene = () => {
  isSelectingFromScene.value = true
  showSceneSelector.value = true
}

const selectToScene = () => {
  isSelectingFromScene.value = false
  showSceneSelector.value = true
}

const handleSceneSelect = (scene: any) => {
  selectedSceneId.value = scene.id
}

const confirmSceneSelection = () => {
  if (!selectedSceneId.value) {
    message.warning('请选择一个场景')
    return
  }
  
  const selectedScene = availableScenes.find(scene => scene.id === selectedSceneId.value)
  if (selectedScene) {
    if (isSelectingFromScene.value) {
      fromSceneThumbnail.value = selectedScene.thumbnail
    } else {
      toSceneThumbnail.value = selectedScene.thumbnail
    }
  }
  
  showSceneSelector.value = false
  selectedSceneId.value = ''
}

const cancelSceneSelection = () => {
  showSceneSelector.value = false
  selectedSceneId.value = ''
}

// 保存过渡效果
const saveTransition = () => {
  message.success('过渡效果已保存')
  // 在实际项目中，这里会调用 API 保存过渡效果数据
}

// 返回上一页
const goBack = () => {
  router.back()
}

// 生命周期钩子
onMounted(() => {
  // 初始化
})
</script>

<style lang="scss" scoped>
.transition-editor-container {
  padding: 20px;
  height: 100%;
  overflow-y: auto;
  
  .transition-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      h1 {
        margin: 0;
        font-size: 24px;
        font-weight: 500;
      }
      
      .header-actions {
        display: flex;
        gap: 12px;
      }
    }
  }
  
  .content-layout {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 24px;
    margin-top: 20px;
    
    .preview-section {
      .preview-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 16px;
        
        h3 {
          margin: 0;
        }
      }
      
      .preview-container {
        border: 1px solid var(--border-color);
        border-radius: 4px;
        overflow: hidden;
        
        .scene-preview {
          position: relative;
          height: 225px;
          background-color: #000;
          
          .scene-from,
          .scene-to {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            
            img {
              width: 100%;
              height: 100%;
              object-fit: cover;
            }
          }
          
          .transition-overlay {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            pointer-events: none;
            
            .transition-effect {
              width: 100%;
              height: 100%;
            }
          }
        }
        
        .preview-controls {
          padding: 16px;
          background-color: var(--card-color);
          
          .progress-labels {
            display: flex;
            justify-content: space-between;
            margin-top: 8px;
            font-size: 12px;
            color: var(--text-color-secondary);
          }
        }
      }
    }
    
    .settings-section {
      border: 1px solid var(--border-color);
      border-radius: 4px;
      overflow: hidden;
      
      .tab-content {
        padding: 16px;
        
        h3 {
          margin-top: 0;
          margin-bottom: 16px;
          font-size: 16px;
        }
      }
    }
  }
  
  .scene-selection {
    margin-top: 24px;
    
    h3 {
      margin-top: 0;
      margin-bottom: 16px;
    }
    
    .scene-selector-container {
      display: flex;
      align-items: center;
      justify-content: space-between;
      
      .scene-selector {
        width: 45%;
        text-align: center;
        
        h4 {
          margin: 0 0 12px;
        }
        
        .scene-thumbnail {
          width: 100%;
          height: 120px;
          margin-bottom: 12px;
          border: 1px solid var(--border-color);
          border-radius: 4px;
          overflow: hidden;
          
          img {
            width: 100%;
            height: 100%;
            object-fit: cover;
          }
        }
      }
      
      .transition-arrow {
        color: var(--text-color-secondary);
      }
    }
  }
  
  .scene-select-item {
    border: 1px solid var(--border-color);
    border-radius: 4px;
    overflow: hidden;
    cursor: pointer;
    transition: transform 0.2s, box-shadow 0.2s;
    
    &.selected {
      border-color: var(--primary-color);
      box-shadow: 0 0 0 2px rgba(var(--primary-color-rgb), 0.2);
    }
    
    img {
      width: 100%;
      height: 80px;
      object-fit: cover;
    }
    
    span {
      display: block;
      padding: 4px 8px;
      font-size: 12px;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
    
    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    }
  }
}

/* 过渡效果样式 */
.effect-fade {
  /* 淡入淡出效果 */
}

.effect-slide {
  /* 滑动效果 */
}

.effect-zoom {
  /* 缩放效果 */
}

.effect-wipe {
  /* 擦除效果 */
}

/* 响应式调整 */
@media (max-width: 768px) {
  .transition-editor-container {
    padding: 10px;
    
    .content-layout {
      grid-template-columns: 1fr;
      
      .settings-section {
        margin-top: 20px;
      }
    }
    
    .scene-selector-container {
      flex-direction: column;
      gap: 16px;
      
      .scene-selector {
        width: 100%;
      }
      
      .transition-arrow {
        transform: rotate(90deg);
      }
    }
  }
}
</style> 